#! /bin/bash
#
# Copyright 2009 Yorba Foundation
#
# This software is licensed under the GNU LGPL (version 2.1 or later).
# See the COPYING file in this distribution. 

# minver <major.minor.revision> <minimum major.minor.revision>
#
# Returns 0 if queried version is greater than or equal to second, 1 otherwise.
# Set VERBOSE environment variable for somewhat useful output.
#
# NOTE:
# This is an ultra-naive implementation with just enough error-checking.

usage() {
    echo 'usage: minver <major.minor.revision> <minimum major.minor.revision>'
}

abort() {
    usage
    exit 1
}

verify_cardinal() {
    while [ $# != 0 ]
    do
        if [ $1 ] && [ $1 -eq $1 2> /dev/null ] && [ $1 -ge 0 ]
        then
            :
        else
            abort
        fi
        
        shift
    done
}

# check_range name number min-number
check_range() {
    if [ $2 -gt $3 ]
    then
        verbose $1 large enough.
        exit 0
    elif [ $2 -lt $3 ]
    then
        verbose $1 not large enough
        exit 1
    fi
}

verbose() {
    if [ $VERBOSE ]
    then
        echo $*
    fi
}

# Check number of arguments
if [ $# -lt 2 ]
then
    abort
fi

# Parse arguments into integers
major=`echo $1 | awk -F. '{print $1}'`
minor=`echo $1 | awk -F. '{print $2}'`
revision=`echo $1 | awk -F. '{print $3}'`

min_major=`echo $2 | awk -F. '{print $1}'`
min_minor=`echo $2 | awk -F. '{print $2}'`
min_revision=`echo $2 | awk -F. '{print $3}'`

# Verify they're all positive integers
verify_cardinal "$major" "$minor" "$revision" "$min_major" "$min_minor" "$min_revision"

verbose Comparing $major.$minor.$revision against $min_major.$min_minor.$min_revision

# check version numbers in order of importance
check_range "Major" $major $min_major
check_range "Minor" $minor $min_minor
check_range "Revision" $revision $min_revision

verbose Same version.
exit 0

